package com.example.myshortcutdemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context

import android.content.Intent

import android.content.pm.ShortcutInfo

import android.content.pm.ShortcutManager
import android.graphics.Bitmap
import android.graphics.drawable.Icon
import android.net.Uri

import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
import com.example.myshortcutdemo.appwidget.ExampleAppWidgetProvider
import com.example.myshortcutdemo.appwidget.NewAppWidget
import com.example.myshortcutdemo.databinding.ActivityMainBinding
import com.example.myshortcutdemo.lekecanary.LeakCanaryCheckActivity
import com.example.myshortcutdemo.lifecycle.LifecycleTestActivity

/**
 *https://developer.android.google.cn/guide/topics/ui/shortcuts/creating-shortcuts
 * https://cloud.tencent.com/developer/article/1444202
 *
 *
 *  止应用不存在时，桌面存在多个应用入口时
 * 打开加载后面的界面后 点击第一个却显示最后一个界面的内容
 *
 * 下面做一个测验查看启动activity时任务栈的情况：
使用adb shell dumpsys activity activities

//这个准一些
adb shell dumpsys activity -p com.example.myshortcutdemo

 * */
class MainActivity : AppCompatActivity() {
    private lateinit var mBind: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBind = DataBindingUtil.setContentView(
            this,
            R.layout.activity_main
        )
        Log.d("自定义的", "onCreate: MainActivity")
        mBind.btAddShortcut.setOnClickListener {
            val iConPath = "https://images.pexels.com/photos/11845527/pexels-photo-11845527.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"
            val iConPath1 = "https://images.pexels.com/photos/2528362/pexels-photo-2528362.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"


         Thread(){
                val bitmap = DownloadImageUtils.downloadImageToBitmap(this, iConPath)
                AddShortCut(
                    this,
                    ShortCutActivity::class.java,
                    MainActivity::class.java,
                    "tgwshotrt",
                    R.drawable.ic_deleted_hint,
                    "动态添加的",
                    bitmap
                )
            }.start()


            Handler(Looper.myLooper()!!).postDelayed({
                Thread(){
                    val bitmap = DownloadImageUtils.downloadImageToBitmap(this, iConPath1)
                    AddShortCut(
                        this,
                        ShortCutActivity::class.java,
                        MainActivity::class.java,
                        "tgwshotrt22",
                        R.drawable.ic_toolbar_bg,
                        "动态添加的2",
                        bitmap
                    )
                }.start()
            },3000)
//            val bitmap = DownloadImageUtils.downloadImageToBitmap(this, iConPath)
//            AddShortCut(
//                this,
//                ShortCutActivity::class.java,
//                MainActivity::class.java,
//                "tgwshotrt",
//                R.drawable.ic_deleted_hint,
//                "动态添加的",
//                bitmap
//            )



//            Handler(Looper.myLooper()!!).post{
//
//                val bitmap = DownloadImageUtils.downloadImageToBitmap(this, iConPath)
//                AddShortCut(
//                    this,
//                    ShortCutActivity::class.java,
//                    MainActivity::class.java,
//                    "tgwshotrt",
//                    R.drawable.ic_deleted_hint,
//                    "动态添加的",
//                    bitmap
//                )
////
//            }


        }

        mBind.btAddDynamicShortcut.setOnClickListener {
            addDynamicShortcut()
        }


        mBind.btAddShortcutCustom.setOnClickListener {
            addShortCutCallback()
        }

        mBind.btAddAppWidget.setOnClickListener {
            createAppWidget()
        }


        mBind.btStartLifecycleTestActivity.setOnClickListener {
           startActivity(Intent(this,LifecycleTestActivity::class.java))
        }

        mBind.btStartLeakTestActivity.setOnClickListener {
           startActivity(Intent(this,LeakCanaryCheckActivity::class.java))
        }
    }

    private fun createAppWidget() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val appWidgetManager: AppWidgetManager =
                getSystemService(AppWidgetManager::class.java)
            val myProvider = ComponentName(this, NewAppWidget::class.java)

            val successCallback: PendingIntent? =
                if (appWidgetManager.isRequestPinAppWidgetSupported) {
                    // Create the PendingIntent object only if your app needs to be notified
                    // that the user allowed the widget to be pinned. Note that, if the pinning
                    // operation fails, your app isn't notified.
                        //这个intent是添加完后的回调,getBroadcast 就是广播
                    Intent(this, ShortCutReceiver::class.java).let { intent ->
                        // Configure the intent so that your app's broadcast receiver gets
                        // the callback successfully. This callback receives the ID of the
                        // newly-pinned widget (EXTRA_APPWIDGET_ID).
                        val pendingIntent: PendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                            PendingIntent.getBroadcast(
                                this,
                                123,
                                intent,
                                PendingIntent.FLAG_IMMUTABLE
                            )
                        } else {
                            PendingIntent.getActivity(
                                this,
                                123,
                                intent,
                                PendingIntent.FLAG_ONE_SHOT
                            )
                        }
                        pendingIntent
                    }
                } else {
                    null
                }

            successCallback?.also { pendingIntent ->
                appWidgetManager.requestPinAppWidget(myProvider, null, pendingIntent)
            }
        }
    }

    private fun addDynamicShortcut() {
        val shortcut = ShortcutInfoCompat.Builder(this, "btAddDynamicShortcut")
            .setShortLabel("Website")
            .setLongLabel("Open the website")
            .setIcon(IconCompat.createWithResource(this, R.drawable.ic_launcher_background))
            .setIntent(
                Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("https://www.mysite.example.com/")
                )
            )
            .build()

        ShortcutManagerCompat.pushDynamicShortcut(this, shortcut)
    }

    private fun addShortCutCallback() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val shortcutManager =
                getSystemService(SHORTCUT_SERVICE) as ShortcutManager
            if (shortcutManager != null && shortcutManager.isRequestPinShortcutSupported) {
                val shortcutInfoIntent = Intent(this, CustomShortCutActivity::class.java)

                shortcutInfoIntent.action = Intent.ACTION_CREATE_SHORTCUT
                val info = ShortcutInfo.Builder(this, "shortCutId")
                    .setIcon(Icon.createWithResource(this, R.drawable.ic_device_mode_welcome))
                    .setShortLabel(
                        "自定义的"
                    ).setIntent(shortcutInfoIntent).build()
                Log.d("自定义的", "自定义的onCreate: ")
                // 可以在此创建intent来通知你用户创建了这个固定快捷方式
                val pinnedShortcutCallbackIntent =
                    shortcutManager.createShortcutResultIntent(info);


                //                    val shortcutCallbackIntent = PendingIntent.getBroadcast(
                //                        this,
                //                        0,
                //                        pinnedShortcutCallbackIntent,
                //                        PendingIntent.FLAG_UPDATE_CURRENT
                //                    )
                //添加成功后，回调用ShortCutReceiver广播，用的getBroadcast 注意要是广播在这才生效
                //已经添加过的话直接会回调广播
                val shortcutCallbackIntent: PendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    PendingIntent.getBroadcast(
                        this,
                        123,
                        intent,
                        PendingIntent.FLAG_IMMUTABLE
                    )
                } else {
                    PendingIntent.getActivity(
                        this,
                        123,
                        Intent(this, ShortCutReceiver::class.java),
                        PendingIntent.FLAG_UPDATE_CURRENT
                    )
                }


                shortcutManager.requestPinShortcut(info, shortcutCallbackIntent.intentSender)

            } else {
                Toast.makeText(this, "设备不支持在桌面创建快捷图标1", Toast.LENGTH_LONG).show()
            }
        } else {
            Toast.makeText(this, "设备不支持在桌面创建快捷图标", Toast.LENGTH_LONG).show()
        }
    }

    /**
     * @param context 当前content
     * @param targetClass 快捷图标打开的界面
     * @param backClass 打开后按返回键返回的界面
     * @param shortCutId shortCut 唯一id
     * @param shortCutIcon 桌面上显示的图标
     * @param shortCutLabel 桌面图标下方显示的文字
     */
    fun AddShortCut(
        context: Context,
        targetClass: Class<*>?,
        backClass: Class<*>?,
        shortCutId: String?,
        shortCutIcon: Int,
        shortCutLabel: String?,
        IconBitmap: Bitmap?=null
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val shortcutManager =
                context.getSystemService(Context.SHORTCUT_SERVICE) as ShortcutManager
            if (shortcutManager != null && shortcutManager.isRequestPinShortcutSupported) {
//                for (short in shortcutManager.getShortcuts(ShortcutManager.FLAG_MATCH_MANIFEST)){
//                    Log.d("AddShortCut", "AddShortCut: ${short.locusId}")
//                }

                val shortcutInfoIntent = Intent(context, targetClass)
                shortcutInfoIntent.putExtra("AddShortCut","addDesktopShortCut")
                shortcutInfoIntent.action = Intent.ACTION_CREATE_SHORTCUT

//                防止应用不存在时，桌面存在多个应用入口时
//                * 打开加载后面的界面后 点击第一个却显示最后一个界面的内容
//                最好使用setIntents
                val emptyIntent = Intent(context,EmptyShortCutActivity::class.java)
                emptyIntent.action = Intent.ACTION_VIEW

                val info = ShortcutInfo.Builder(context, shortCutId)
//                    .setIcon(Icon.createWithResource(context, shortCutIcon)).setShortLabel(
                    .setIcon(Icon.createWithBitmap(IconBitmap))
                    .setShortLabel(
                        shortCutLabel!!
                    ).setIntents(arrayOf(emptyIntent,shortcutInfoIntent)).build()

//                // 可以在此创建intent来通知你用户创建了这个固定快捷方式
//                val pinnedShortcutCallbackIntent =
//                shortcutManager.createShortcutResultIntent(info);
                val shortcutCallbackIntent: PendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    PendingIntent.getBroadcast(
                        this,
                        123,
                        Intent(this, ShortCutReceiver::class.java),
                        PendingIntent.FLAG_IMMUTABLE
                    )
                } else {
                    PendingIntent.getActivity(
                        this,
                        123,
                        Intent(this, ShortCutReceiver::class.java),
                        PendingIntent.FLAG_UPDATE_CURRENT
                    )
                }

//                val shortcutCallbackIntent = PendingIntent.getBroadcast(
//                    context,
//                    0,
//                    Intent(context, backClass),
//                    PendingIntent.FLAG_UPDATE_CURRENT
//                )
                shortcutManager.requestPinShortcut(info, shortcutCallbackIntent.intentSender)
                shortcutManager.updateShortcuts(arrayListOf(info))
            } else {
                Log.d("AddShortCut1", "AddShortCut: ")
//                Toast.makeText(this, "设备不支持在桌面创建快捷图标1", Toast.LENGTH_LONG).show()
            }
        } else {
            Log.d("AddShortCut2", "AddShortCut: ")

//            Toast.makeText(this, "设备不支持在桌面创建快捷图标", Toast.LENGTH_LONG).show()
        }
    }

    fun AddShortCut1(
        context: Context,
        targetClass: Class<*>?,
        backClass: Class<*>?,
        shortCutId: String?,
        shortCutIcon: Int,
        shortCutLabel: String?,
        IconBitmap: Bitmap?=null
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val shortcutManager =
                context.getSystemService(Context.SHORTCUT_SERVICE) as ShortcutManager
            if (shortcutManager != null && shortcutManager.isRequestPinShortcutSupported) {
//                for (short in shortcutManager.getShortcuts(ShortcutManager.FLAG_MATCH_MANIFEST)){
//                    Log.d("AddShortCut", "AddShortCut: ${short.locusId}")
//                }

                val shortcutInfoIntent = Intent(context, targetClass)
                shortcutInfoIntent.putExtra("AddShortCut","addDesktopShortCut")
                shortcutInfoIntent.action = Intent.ACTION_CREATE_SHORTCUT

//                防止应用不存在时，桌面存在多个应用入口时
//                * 打开加载后面的界面后 点击第一个却显示最后一个界面的内容
//                最好使用setIntents
                val emptyIntent = Intent(context,EmptyShortCutActivity::class.java)
                emptyIntent.action = Intent.ACTION_VIEW

                val info = ShortcutInfo.Builder(context, shortCutId)
//                    .setIcon(Icon.createWithResource(context, shortCutIcon)).setShortLabel(
                    .setIcon(Icon.createWithBitmap(IconBitmap))
                    .setShortLabel(
                        shortCutLabel!!
                    ).setIntents(arrayOf(shortcutInfoIntent)).build()

//                // 可以在此创建intent来通知你用户创建了这个固定快捷方式
//                val pinnedShortcutCallbackIntent =
//                shortcutManager.createShortcutResultIntent(info);
                val shortcutCallbackIntent: PendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    PendingIntent.getBroadcast(
                        this,
                        123,
                        Intent(this, ShortCutReceiver::class.java),
                        PendingIntent.FLAG_IMMUTABLE
                    )
                } else {
                    PendingIntent.getActivity(
                        this,
                        123,
                        Intent(this, ShortCutReceiver::class.java),
                        PendingIntent.FLAG_UPDATE_CURRENT
                    )
                }

//                val shortcutCallbackIntent = PendingIntent.getBroadcast(
//                    context,
//                    0,
//                    Intent(context, backClass),
//                    PendingIntent.FLAG_UPDATE_CURRENT
//                )
                shortcutManager.requestPinShortcut(info, shortcutCallbackIntent.intentSender)
                shortcutManager.updateShortcuts(arrayListOf(info))
            } else {
                Log.d("AddShortCut1", "AddShortCut: ")
//                Toast.makeText(this, "设备不支持在桌面创建快捷图标1", Toast.LENGTH_LONG).show()
            }
        } else {
            Log.d("AddShortCut2", "AddShortCut: ")

//            Toast.makeText(this, "设备不支持在桌面创建快捷图标", Toast.LENGTH_LONG).show()
        }
    }
}